package com.feige.controller;


import com.feige.constant.Constants;
import com.feige.pojo.User;
import com.feige.pojo.UserCourse;
import com.feige.pojo.vo.UserVo;
import com.feige.result.AjaxResult;
import com.feige.result.R;
import com.feige.service.UserCourseService;
import com.feige.utils.redis.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 用户课程表 前端控制器
 * </p>
 *
 * @author feige
 * @since 2020-11-20
 */
@Api(tags = "用户课程控制类")
@RestController
@RequestMapping("/course/user-course")
public class UserCourseController {

    @Resource
    private UserCourseService userCourseService;

    @Resource
    private RedisUtils redisUtils;


    @ApiOperation(value = "加入一门课程")
    @PostMapping("/join")
    public AjaxResult joinCourse(@Validated @RequestBody UserCourse userCourse){
        String key = Constants.GROUP_USER_ID_KEY + userCourse.getCourseId();
        // 群聊需要，可以查看ChatHandler.java
        // 保证缓存的中的用户ID和MySQL的一致
        boolean hasKey = redisUtils.hasKey(key);
        if (hasKey) {
            redisUtils.lSet(key,userCourse.getUserId());
        }
        return userCourseService.joinCourse(userCourse);
    }


    @ApiOperation(value = "获取课程对应的用户")
    @GetMapping("/{pageNum}/{courseId}")
    public AjaxResult getCourseUser(@PathVariable Integer pageNum,@PathVariable String courseId){
        List<User> users = userCourseService.getCourseUser(courseId,pageNum);
        int total = userCourseService.getCourseUserCount(courseId);
        AjaxResult success = AjaxResult.success(users);
        success.put("total",total);
        return success;
    }

    @ApiOperation(value = "把用户踢出课程")
    @DeleteMapping("/delete/{userId}/{courseId}")
    public AjaxResult delete(@PathVariable String userId, @PathVariable String courseId){
        String key = Constants.GROUP_USER_ID_KEY + courseId;
        // 群聊需要，可以查看ChatHandler.java
        // 保证缓存的中的用户ID和MySQL的一致
        boolean hasKey = redisUtils.hasKey(key);
        if (hasKey) {
            redisUtils.lRemove(key,1,userId);
        }
        return userCourseService.kickOut(userId,courseId);
    }

    @GetMapping("/ids/{courseId}/{userId}")
    public R<List<Object>> getUserIdsByCourseId(@PathVariable("courseId") String courseId, @PathVariable("userId") String userId){
        return R.ok(userCourseService.getUserIdsByCourseId(courseId,userId));
    }

    @GetMapping("/userVo/{courseId}")
    public R<List<UserVo>> getCourseUserVoByCourseId(@PathVariable("courseId") String courseId){
        return R.ok(userCourseService.getCourseUserVoByCourseId(courseId));
    }
}

